import pymysql
from pymysql import Error

def test_mysql_connection():
    try:
        # 连接参数
        connection = pymysql.connect(
            host='localhost',      # 数据库主机地址
            user='root',          # 数据库用户名
            password='mysql',    # 数据库密码
            database='weather_db', # 数据库名称
            charset='utf8mb4'
        )

        print("成功连接到MySQL数据库！")

        # 创建游标
        with connection.cursor() as cursor:
            # 测试查询
            cursor.execute("SELECT VERSION()")
            version = cursor.fetchone()
            print(f"MySQL版本: {version[0]}")

            cursor.execute("SELECT DATABASE()")
            database = cursor.fetchone()
            print(f"当前数据库: {database[0]}")

    except Error as e:
        print(f"连接出错: {e}")

    finally:
        if 'connection' in locals():
            connection.close()
            print("MySQL连接已关闭")

if __name__ == "__main__":
    test_mysql_connection()